package com.yuchengtech.simpleServer.core.handler;

import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.Map;


import sun.net.www.protocol.http.HttpURLConnection;

import com.yuchengtech.simpleServer.core.HttpRequest;
import com.yuchengtech.simpleServer.core.HttpResponse;
import com.yuchengtech.simpleServer.core.SimpleHttpServer;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class FreemarkerHandler implements Handler {

	
	private static FreemarkerHandler handler;
	
	
	private Configuration cfg;
	
	public FreemarkerHandler() {
		cfg=new Configuration();
		try {
			cfg.setDirectoryForTemplateLoading(new File(SimpleHttpServer.getBasePath()));
			cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); 
			//cfg.setObjectWrapper(new DefaultObjectWrapper());
		
		} catch (IOException e) {
		}
	}
	
	public void doHandle(Socket connection, HttpRequest request,
			HttpResponse response) {
		try {
			Map<String,Object> root=request.getAttributeMap();
			root.putAll(request.getParameterMap());
			
			try{
				Template t=cfg.getTemplate(request.getNowUrl());
				t.process(root, response.getPrintWriter());
			} catch (TemplateException e) {
				response.setStatusCode(HttpURLConnection.HTTP_NOT_FOUND);
			}
			response.doResponse();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public static FreemarkerHandler getHandler()
	{
		if(handler==null)
			handler=new FreemarkerHandler();
			
		return handler;
		
	}
}
